package com.zy.pro.user.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zy.core.service.impl.ServiceSupport;
import com.zy.pro.user.dao.UserMapper;
import com.zy.pro.user.model.User;
import com.zy.pro.user.service.UserService;
import com.zy.utils.MailInfo;
import com.zy.utils.MethodUtil;
import com.zy.utils.SimpleMailSender;
@Service
public class UserServiceImpl extends ServiceSupport<User> implements UserService {

	@Autowired
    private UserMapper<User> mapper;

	public UserMapper<User> getMapper() {
		return mapper;
	}

	@Override
	public User findUserNameAndPassword(User user) {
		return mapper.findUserNameAndPassword(user);
	}

	@Override
	public String saveUser(User user, HttpServletRequest request) throws Exception {
		mapper.insert(user);
		//根据路径读取内容,如果内容中含有链接地址(ubuntu系统下链接路径中不需要+http://如:<a href='52.10.236.16:8080/decor'></a>)
		MailInfo mailInfo = MailInfo.getInstance(request);
//		String message = "Please click the following link to activate your account<br><a href='"+mailInfo.getProperty("mailPath")+"control/user/userController/activateAccount.do?userId="+user.getUserId()+"'>Click on the activate</a>";
		String msg = SimpleMailSender.sendFileMail(user.getEmail(), 
				mailInfo.getProperty("mailName"), 
				mailInfo.getProperty("mailPassword"), 
				"Please click the following link to activate your account<br><a href='"+mailInfo.getProperty("mailPath")+"control/user/userController/activateAccount.do?userId="+user.getUserId()+"'>Click on the activate</a>", 
				"To activate the account");
		//如果邮件发送失败,删除已经注册的用户信息
		if(msg != null && !"".equals(msg) && "email error".equals(msg) && user != null && user.getUserId() != null){
			mapper.delete(user.getUserId());
		}
		return msg;
	}

	@Override
	public User findUserByEamilAndUserName(User user) {
		return mapper.findUserByEamilAndUserName(user);
	}

	@Override
	public String updateRsetPasswordAndToEmail(User user,HttpServletRequest request) throws Exception {
		User userInfo = new User();
		//初始化密码为123456
		userInfo.setUserId(user.getUserId());
		userInfo.setPassword(MethodUtil.MD5("123456"));
		mapper.updateBySelective(userInfo);
		//根据路径读取内容
		//将用户信息(用户名和密码发送到用户邮箱)
		MailInfo mailInfo = MailInfo.getInstance(request);
		String msg = SimpleMailSender.sendFileMail(user.getEmail(), 
				mailInfo.getProperty("mailName"), 
				mailInfo.getProperty("mailPassword"), 
				"Hello, your username is: "+user.getUserName()+", initialize your password: 123456.<br>Please after you log in to reset your password as soon as possible, keep the password", 
				"Password back");
		return msg;
	}

	@Override
	public User findUserByUserName(User user) {
		return mapper.findUserByUserName(user);
	}
		
	
}
